package myalg.graphs.ui;

import myalg.graphs.Edge;
import myalg.graphs.Graph;
import myalg.graphs.Vertex;
import myalg.graphs.alg.AlgorithmListener;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;

/**
 * @author Pavel Belevich
 *         Date: Jun 13, 2012
 *         Time: 2:37:48 PM
 */
public class GraphPanel extends JPanel implements AlgorithmListener {

    private Graph graph;

    public GraphPanel(Graph graph) {
        this.graph = graph;
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D) g;

        double cx = getWidth() / 2;
        double cy = getHeight() / 2;

        for (Edge edge : graph.getEgdes()) {
            Shape s = new Line2D.Double(
                    cx + edge.getV1().getX(), cy - edge.getV1().getY(),
                    cx + edge.getV2().getX(), cy - edge.getV2().getY()
            );
            g2.setColor(edge.getColor());
            g2.draw(s);

            String caption = graph.getCaption().getCaption(edge);
            g2.drawString(caption == null ? "" : graph.getCaption().getCaption(edge),
                    (float)(cx + (edge.getV1().getX() + edge.getV2().getX()) / 2.0 + 6),
                    (float)(cy - (edge.getV1().getY() + edge.getV2().getY()) / 2.0 - 6)
            );
        }

        for (Vertex vertex : graph.getVertices()) {
            Shape s = new Ellipse2D.Double(cx + vertex.getX() - vertex.getRadius(), cy - vertex.getY() - vertex.getRadius(), 2.0 * vertex.getRadius(), 2.0 * vertex.getRadius());
            g2.setColor(vertex.getColor());
            g2.fill(s);

            String caption = graph.getCaption().getCaption(vertex);
            g2.drawString(caption == null ? "" : caption,
                    (float)(cx + vertex.getX() + 6),
                    (float)(cy - vertex.getY() - 6)
            );
        }
        
    }

    @Override
    public void step() {
        this.repaint();
    }
}
